<?php
/**
 * FastApp.
 * 8/17/24
 * @Author 深色的海 (wx:deepsea_0024)
 * @Contact telegram:deepsea159
 */

namespace App\Mall\Api\Service;

use App\Mall\Model\MallGoods;
use App\Mall\Model\MallGoodsCategory;
use App\Mall\Model\MallGoodsTag;

class GoodsService
{
    public function list(array $param = []): array
    {
        $table = MallGoods::getModel()->getTable();
        $query = MallGoods::query();
        if (!empty($param['category_id'])) {
            $query->join(MallGoodsCategory::getModel()->getTable() . ' as b', $table . '.id', '=', 'b.goods_id');
            $query->whereRaw('b.category_id=' . ((int)$param['category_id']));
        }
        if (!empty($param['tag_id'])) {
            $query->join(MallGoodsTag::getModel()->getTable() . ' as c', $table . '.id', '=', 'c.goods_id');
            $query->whereRaw('c.tag_id=' . ((int)$param['tag_id']));
        }
        $list = $query->with(['spec', 'brand'])->select([
            $table . '.id', 'name', 'title', 'images',
            'shop_id', 'is_spec', 'comments', 'views',
            'collects', 'brand_id', 'no'
        ])
            ->where(['online' => 1])->orderByDesc('sort')->orderByDesc('id')
            ->get()->map(function ($item) {
                $this->extracted($item);
                return $item;
            });
        return ['list' => $list];
    }

    public function detail(int $id): array
    {
        $item = MallGoods::query()->with(['spec', 'brand'])->where(['id' => $id])->firstOrFail();
        $this->extracted($item);
        return $item->toArray();
    }

    public function extracted(MallGoods $item): void
    {
        $item->name = fastapp_lang_text($item->name);
        $item->title = fastapp_lang_text($item->title);
        if ($item->content) $item->content = fastapp_lang_text($item->content);
        if ($item->brand && $item->brand->name) $item->brand->name = fastapp_lang_text($item->brand->name);
        $n = $item->spec->count();
        if ($n) {
            foreach ($item->spec as $spec) {
                $spec->name = $spec->name ? fastapp_lang_text($spec->name) : '';
                if ($spec->price?->count()) {
                    $spec->setHidden(['price']);
                    $spec->prices = $spec->price->pluck('price', 'symbol');
                }
            }
        }
    }
}